package org.example.library.service;

import org.example.library.pojo.User;
import org.example.library.pojo.dto.UserDto;
import org.example.library.repository.IUserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService implements IUserService {

    @Autowired
    IUserRepository _userRepository;



    @Override
    public User add(UserDto user) {
        User userPojo = new User();
        BeanUtils.copyProperties(user,userPojo);
        return _userRepository.save(userPojo);
        //调用数据访问类

    }

    @Override
    public User getUser(Integer userId) {
        return _userRepository.findById(userId).orElseThrow(() -> {
            throw new IllegalArgumentException("用户不存在，参数异常！");
        });
    }

    @Override
    public User edit(UserDto user) {
        User userPojo = new User();
        BeanUtils.copyProperties(user,userPojo);
        // 打印日志检查 userId 是否被正确复制
        System.out.println("Editing user with ID: " + userPojo.getUserID());
        return _userRepository.save(userPojo);
    }

    @Override
    public User delete(Integer userId) {
        _userRepository.deleteById(userId);
        return null;
    }
}
